<template>
	<view>
		<!-- 头部信息 -->
		<j-header ref="jheader" :deviceList="deviceList" :allDeviceList="allDeviceList" :shareDeviceList="sharedDeviceList" navigate="device"
			@loadhandler="onLoadHandler"></j-header>
			
		<!-- #ifdef MP-WEIXIN -->
		<adddevice ref="adddevice" />
		<!-- #endif -->
		<!-- 有设备时 -->
		<template>
			<view class="tab-box" style="">
				<tab @sendWebsocketInfo="sendWebsocketInfo" @editEmptyFlag="editEmptyFlag" ref="tab" :isBack="isBack" :deviceNo="deviceNo" :sns="sns"></tab>
			</view>
		</template>
		<!-- 无设备时 -->
		<template v-if="sharedDeviceList.length==0 && deviceList.length == 0 && emptyFlag == 1">
			<view class="bottom-fixed" :style="{bottom:windowHeight+'px'}">
				<view style="margin-top: -40px;" @tap="onBindtapAddDevice">
					<image :src="'https://statics.xmcsrv.net/weixin/Telkomsel/addDevice.png'" mode="aspectFit"></image>
					<view>{{$t('General.add.addDevice')}}</view>
				</view>
			</view>
		</template>
	</view>
</template>

<script>
	const {
		splitArray
	} = require('@/utils/util.js');
	import tab from './tab/tab';
	import adddevice from './adddevice/adddevice';
	export default {
		components: {
			tab,
			adddevice
		},
		data() {
			return {
				deviceList: [], // 设备列表
				sharedDeviceList:[],// 分享的设备列表
				img: '',
				isBack: false,
				deviceNo: '',
				allDeviceList: [],
				sns: [],
				isShowStatusModal: false,
				emptyFlag: 0,
				roomId: '',
				localUiKey: '',
				windowHeight:''
			};
		},
		provide() {
			return {
				getShareInfo: this.getShareInfo
			}
		},
		onLoad() {
			uni.$on('onWebsocketMessage', (res) => {
				this.websocketInfo(res);
				this.getAllDeviceListByPage()
				setTimeout(() => {
					this.$refs.tab.websocketInfo(res);
				}, 100)
			})
			if (uni.getStorageSync('accessToken')) {
				this.getCode()
			}
			let statusBarHeight = uni.getSystemInfoSync().statusBarHeight
			uni.setStorageSync('statusBarHeight', statusBarHeight * (750 / uni.getSystemInfoSync().windowWidth))
			// #ifdef MP-WEIXIN
			let menuButtonObject = uni.getMenuButtonBoundingClientRect();
			let navHeight = menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2;
			uni.setStorageSync('navHeight', navHeight * (750 / uni.getSystemInfoSync().windowWidth))
			wx.hideShareMenu()
			// #endif
			this.getClipboardData(); //获取剪切板
		},
		onUnload() {
			console.log('哎就是打卡机艾迪卡就俺仨')
			this.closeOnceEvent()
			uni.$off('delDevice')
			uni.$off('chooseRoom')
			uni.$off('moveRoom')
			uni.$off('editDeviceName')
			uni.$off('getSharedDeviceList')
			uni.setStorageSync('isOnWebsocket', false)
		},
		onHide() {
			this.isBack = false
		},
		onShow() {
            uni.setNavigationBarTitle({
                title: this.$t('General.home.device')
            });

            let sys = uni.getSystemInfoSync();
			this.windowHeight = (sys.windowHeight-90)/2 - 120 ;
			console.log(this.windowHeight,'windowHeight')
			this.$logs({
				info: '进入小程序首页=== home:onShow:'
			})
			// 如果设备处于在线状态且 StartFlag为true，发送end指令
			const startFlag = uni.getStorageSync('StartFlag');
			if (startFlag && startFlag.token) {
			    this.getDeviceStatus([startFlag.token]);
			    if (startFlag.start === true && uni.getStorageSync(startFlag.deviceNo).status.status === 'online') {
			        this.sendEnd();
			    }
			}
			this.getAllDeviceListByPage('all')
			if (uni.getStorageSync('adddevice') == 1) {
				this.$refs.adddevice.closeBluetoothAdapter()
			}
			let currentGroupId = uni.getStorageSync('currentGroupId')
			if (currentGroupId) {
				this.getDeviceListByPage({
					currentGroupId: currentGroupId,
					roomId: this.roomId ? this.roomId : null
				}, this.roomId ? 2 : '')
			}
			this.clearKeepAliveTimer()
			this.onOnceEvent()
			this.getUserDeviceListByPage()
		},
		//发送给朋友
		onShareAppMessage(res) {
			return {
				title: '和我一起控制家里的设备和智能场景',
				path: '/jvss/pagesDevice/share/share?shareMessage=' + encodeURIComponent(this.shareMessage),
				imageUrl: "https://statics.xmcsrv.net/weixin/share_bg.png"
			}
		},
		onReady() {
			uni.$on('delDevice', (res) => {
				this.getDeviceListByPage({
					currentGroupId: uni.getStorageSync('currentGroupId')
				})
			})
			uni.$on('chooseRoom', (res) => {
				this.roomId = res.roomId
				let data = {
					roomId: res.roomId,
					currentGroupId: uni.getStorageSync('currentGroupId')
				}
				this.getDeviceListByPage(data, 2)
			})
			uni.$on('getSharedDeviceList', (res) => {
				if(res && res.length > 0){
					this.sharedDeviceList = res
					let sns = []
					res.forEach((item)=>{
						sns.push(item.deviceNo)
					})
					this.sendWebsocketInfo(sns) //订阅设备
					console.log('订阅分享的或设备',sns);
				}
			})
			let currentPage = getCurrentPages()
			// console.log('当前页===',currentPage);
		},
		onPullDownRefresh() {
			this.$logs({
				info: '下拉刷新保活定时器-home',
				data: getApp().globalData.keepTimer
			})
		},
		methods: {
			getShareInfo(e) {
				this.shareMessage = e;
			},
			//预览页的事件监听
			onOnceEvent() {
				this.closeOnceEvent()
				let that = this
				uni.$once('deviceLogout', function(data) {
					console.log('从预览页退出data===', data);
					if (data.localUiKey != 'ui_doorlock_home') {
						that.isBack = data.isBack
					}
					that.deviceNo = data.deviceNo
					that.localUiKey = data.localUiKey
					that.clearKeepAliveTimer()
				})
				uni.$once('getLoginSuccess', function(data) {
					if (data.isLogout) {
						that.clearKeepAliveTimer()
						that.deviceLogOut(data.token)
						that.$logs({
							info: '快速退出预览页后到首页才登录成功',
							timer: getApp().globalData.keepTimer,
							data: data
						})
					}
				})
				uni.$once('getLiveStream', function(data) {
					if (data.isLogout) {
						that.clearKeepAliveTimer()
						that.closeLivestream(data, 'live')
						uni.hideLoading()
						that.$logs({
							info: '快速退出预览页后到首页才获取到直播地址',
							timer: getApp().globalData.keepTimer,
							data: data
						})
					}
				})
				uni.$once('getTalkUrl', function(data) {
					console.log('快速退出预览页后到首页才获取到对讲地址', data.isLogout);
					if (data.isLogout) {
						that.clearKeepAliveTimer()
						that.closeLivestream(data, 'talk')
						uni.hideLoading()
						that.$logs({
							info: '快速退出预览页后到首页才获取到对讲地址',
							timer: getApp().globalData.keepTimer,
							data: data
						})
					}
				})
				uni.$once('getKeepAlive', function(data) {
					if (data.isLogout) {
						that.$logs({
							info: '快速退出预览页后到首页才获取到保活接口',
							timer: getApp().globalData.keepTimer,
							data: data
						})
						that.clearKeepAliveTimer()
					}
				})
			},
			//关闭预览页事件监听
			closeOnceEvent() {
				uni.$off('deviceLogout')
				uni.$off('getLoginSuccess')
				uni.$off('getLiveStream')
				uni.$off('getTalkUrl')
				uni.$off('getKeepAlive')
			},
			websocketInfo(res) {
				// console.log('home首页接收mqtt消息', JSON.parse(res));
				let info = JSON.parse(res)
				let userinfo = uni.getStorageSync('userInfo');
				if (info) {
					info.props.forEach((item) => {
						// 家庭下添加设备
						if (item.propCode == "deviceAdd") {
							if (item.propValue.userGroupId == uni.getStorageSync('currentGroupId')) {
								this.emitGetRoomListByPage('refresh')
							};
						}
						// 家庭下用户被设备
						if (item.propCode == "userDel") {
							if (userinfo.userId == item.propValue.userId) {
								setTimeout(() => {
									this.$refs.jheader.getUserGroupListByPage()
								}, 2000)
							}
						}
					})
				}
			},
			//快速退出预览页面时  没有调登出接口
			clearKeepAliveTimer() {
				if (getApp().globalData.keepTimer) {
					uni.$off('getKeepAlive')
					clearInterval(getApp().globalData.keepTimer);
					getApp().globalData.keepTimer = null
					this.$logs({
						info: 'home清除保活定时器',
						data: getApp().globalData.keepTimer
					})
				}
			},
			//设备退出
			deviceLogOut(token) {
				let data = {
					Name: 'Logout',
				};
				getApp().globalData.api.deviceLogOut(data, token, (result) => {
					console.log(result, '首页登出')
					// uni.$off('getLoginSuccess')
					this.$logs({
						info: '首页登出',
						data: result
					})
				});
			},
			//关闭设备流
			closeLivestream(device, type) {
				let token = device.token
				const data = {
					channel: '0',
					stream: device.stream,
					PassWord: device.devPassWord,
					UserName: device.devUserName,
					encryptType: 'DISABLE',
					authentication: device.authentication
				};
				getApp().globalData.api.closeLivestream(data, token, (result) => {
					this.$logs({
						info: '首页关闭设备码流',
						sn: device.deviceNo,
						data: data,
						result: result.data
					})
					if (type == 'live') {
						// uni.$off('getLiveStream')
					} else if (type == 'talk') {
						// uni.$off('getTalkUrl')
					}
				}, false, false);
			},
			/** ======================== emit事件 ================================ */
			// 页面入口函数
			// 获取房间列表之前，必须先获取当前家庭组
			// 初始化页面时，会执行这个函数
			onLoadHandler(options, type) {
				this.emptyFlag = 0;
				setTimeout(() => {
					this.$refs.tab.currentRoom.id = '';
					this.$refs.tab.newList = [];
				})
				this.$refs.tab.roomList = []
				this.$refs.tab.onSwitchRooms({
					id: ''
				});
				if (options.hasOwnProperty('currentGroupId')) {
					this.getDeviceListByPage(options)
				}
			},
			// 家庭组接收消息刷新tab组件 家庭列表
			emitGetRoomListByPage(type) {
				this.emptyFlag = 0;
				console.log(this.emptyFlag, '新增设备')
				if (type) {
					this.$refs.tab.getRoomListByPage(type);
				} else {
					this.$refs.tab.getRoomListByPage(true);
				}
			},
			getUserDeviceListByPage() {
				const data = {
					page: 1,
					limit: 999,
				};
				getApp().globalData.api.getUserDeviceListByPage(data, (result) => {
					// console.log(result.data, 'result.data')
					uni.setStorageSync('allDeviceList', result.data)
				});
			},
			// 分页查询设备列表
			getDeviceListByPage(options, type) {
				// console.log(type,options,'======================查询设备列表');
				const data = {
					userGroupId: options.currentGroupId ? options.currentGroupId : null,
					page: 1,
					limit: 999,
					roomId: options.roomId || ''
				};
				getApp().globalData.api.getDeviceListByPage(data, (result) => {
					this.deviceList = result.data
					let sns = [];
					this.deviceList.forEach((item) => {
						sns.push(item.deviceNo);
					});
					if (type == 2) {
						let roomId = options.roomId
						let list = []
						result.data.forEach((item) => {
							if (roomId == item.roomId) {
								list.push(item)
							}
						})
						this.deviceList = roomId ? list : result.data
					}
					if (type == 3) {
						console.log(result, '查询所有')
					}
				});
			},
			editEmptyFlag(e) {
				this.emptyFlag = e;
			},
			// 添加设备（扫描） TODO
			onBindtapAddDevice(ev) {
				uni.$emit('stopBlue')
				uni.navigateTo({
					url: '/jvss/pagesDevice/device/device-add/device-add'
				});
			},
			// 是否有邀请码，并且被加入用户组
			getClipboardData() {
				uni.getClipboardData({
					success: res => {
						// console.log('获取剪切板邀请码：', res)
						uni.hideToast();
						if (res.errMsg === 'getClipboardData:ok' && res.data !== '') {
							// this.decodeKey(res.data)
							if (res.data.includes('请长按复制邀请码，打开app加入用户组')) {
								if (uni.getStorageSync('inviteCode') != res.data.split(':')[1]) {
									this.decodeKey(res.data)
									uni.setStorageSync('inviteCode', res.data.split(':')[1])
								}
							}
						}
					}
				})
			},
			// 解析邀请口令
			decodeKey(key) {
				const data = {
					key: key
				}
				// 解析邀请码
				getApp().globalData.api.decodeKey(data, result => {
					// console.log('解析邀请码：', result);
					if (result.data.code === 2000) {
						// 用户操作是否加入家庭组
						uni.showModal({
							title: '提示',
							content: `是否加入家庭组【${result.data.data.userGroupName}】`,
							success: res => {
								if (res.confirm) {
									this.addUser(key)
								}
							},
							fail(err) {},
							complete() {
								uni.setClipboardData({
									data: ' ',
									success(res) {
										uni.hideToast()
									}
								})
							}
						})
					} else {
						uni.showToast({
							title: result.data.msg,
							duration: 2000,
							icon: 'none',
							success: (res) => {
								setTimeout(() => {
									uni.setClipboardData({
										data: ' ',
										success(res) {
											uni.hideToast()
										},
										fail: (err) => {}
									})
								}, 1000)
							}
						});
					}
				})
			},
			// 加入家庭
			addUser(key) {
				const params = {
					userName: uni.getStorageSync('userInfo').nickName || uni.getStorageSync('userInfo').nickname,
					key: key,
				}
				// 添加用户到家庭组
				getApp().globalData.api.addUser(params, result => {
					// console.log('当前用户加入到用户组:', result);
					this.$refs.jheader.getUserGroupListByPage()
				})
			},
			//获取code
			getCode() {
				wx.login({
					success: (res) => {
						if (res.code) {
							this.judgeIsFollowOffcialAccount(res.code)
						} else {
							// console.log('登录失败！' + res.errMsg)
						}
					}
				})
			},
			judgeIsFollowOffcialAccount(code) {
				let data = {
					code: code,
				}
				getApp().globalData.api.getDeviceAuth(data, (result) => {
					let isOfficialAccounts = uni.getStorageSync('isOfficialAccounts')
					if (!result.authed && isOfficialAccounts) {
						uni.showModal({
							title: '提示',
							content: '请搜索“小峰管家”微信公众号关注并开通消息提醒才会收到设备推送消息哦！',
							confirmText: '确定',
							showCancel: false,
							success: (res) => {
								if (res.confirm) {}
							}
						})
					}
				})
			},
			//websocket发送消息
			sendWebsocketInfo(sns) {
				let topic = [];
				let newTopics = [];
				sns.forEach((item) => {
					topic.push(`/device/${item}`);
					newTopics.push(`/device/${item}/alarmEvent`);
				})
				let arr = splitArray(topic, 20);
				let newArr = splitArray(newTopics, 20);
				if (arr.length > 0) {
					arr.forEach((item) => {
						getApp().globalData.mqtt.subscribe(item)
					})
				}
				if (newArr.length > 0) {
					newArr.forEach((item) => {
						getApp().globalData.mqtt.subscribe(item);
					});
				}
			},
			// 查询所有设备列表
			getAllDeviceListByPage(type) {
				const data = {};
				getApp().globalData.api.getAllDeviceList(data, (result) => {
					// console.log('所有设备列表:', result);
					let sns = [];
					let allSns = []
					let readList = []
					let status = uni.getStorageSync('readStatus')
					let add = [...status]
					if (!status) {
						result.forEach((item) => {
							let obj = {}
							obj.deviceNo = item.deviceNo
							obj.readStatus = true
							readList.push(obj)
							allSns.push(item.deviceNo)
							if (!item.deviceNo.includes('vir')) {
								this.allDeviceList.push(item)
								// sns.push(item.deviceNo)
							}
						})
						uni.setStorageSync('readStatus', readList)
					} else {
						for (let i = 0; i < result.length; i++) {
							for (let j = 0; j < status.length; j++) {
								if (result[i].deviceNo != status[j].deviceNo) {
									if (j == status.length - 1) {
										add.push({
											deviceNo: result[i].deviceNo,
											readStatus: false
										})
									} else continue
								} else {
									break
								}
							}
						}
						uni.setStorageSync('readStatus', add)
					}
					if (type == 'all') {
						// 谨慎修改
						this.allDeviceList = []
						result.forEach((item) => {
							if (!item.deviceNo.includes('vir')) {
								sns.push(item.deviceNo)
								this.allDeviceList.push(item)
							}
						})
					}
					this.sns = allSns
					this.sendWebsocketInfo(sns) //订阅设备
					if (sns.length > 0) {
						this.getDeviceToken(sns);
					}
				})
			},
			// 获取设备token
			getDeviceToken(sns) {
				const data = {
					sns: sns
				};
				getApp().globalData.api.getDeviceToken(data, (result) => {
					// console.log('获取设备token:', result);
					let tokenList = [];
					result.forEach((pro) => {
						tokenList.push(pro.token);
					});
					this.allDeviceList.forEach((item) => {
						this.$set(item, 'isSelected', false)
						result.forEach((pro) => {
							if (item.deviceNo === pro.sn) {
								item.token = pro.token;
							}
						});
					});
					// console.log('获取设备token:', this.allDeviceList);
					this.subscribeAllDevice(this.allDeviceList)
					this.getDeviceStatus(tokenList)
				});
			},
			// 获取状态
			getDeviceStatus(tokenList) {
				const data = {
					otherStatus:true,
					token: tokenList
				};
				getApp().globalData.api.getDeviceStatus(data, (result) => {
					result.forEach((item) => {
						let cacheData = uni.getStorageSync(item.uuid)
						if (!cacheData) {
							uni.setStorageSync(item.uuid, {
								status: item
							})
						} else {
							cacheData['status'] = item
							uni.setStorageSync(item.uuid, cacheData)
						}
					})
				})
			},
			//订阅所有设备
			subscribeAllDevice(list) {
				let subscribeList = []
				list.forEach((item) => {
					subscribeList.push({
						sn: item.deviceNo,
						token: item.token
					})
				})
				let data = {
					subscribeList: subscribeList
				}
				getApp().globalData.api.subscribeAllDeviceBatchSubscribe(data, (result) => {});
			},
			// 发送End结束流程
			sendEnd(){
				let data = {
					Name: 'OPDoorLockProCmd',
					OPDoorLockProCmd: {
						Cmd: "SyncDoorStatus",
						DoorStatus: {
							Status:'End'
						},
						SessionID: 0x00000001
					}
				};
				let token = uni.getStorageSync('StartFlag').token;
				getApp().globalData.api.doorLockTransparent(data, token, (result) => {
					if (result.data.code == 2000) {
						if(result.data.data.Ret==100){
							console.log('发送End成功',result);
							// flag缓存置空
							uni.setStorageSync('StartFlag',{})
						}
					}else{
						// uni.showToast({
						// 	title:getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data.msg,
						// 	icon: 'none',
						// 	duration:2000
						// });
					}
				},false);
			}
		}
	};
</script>
<style>
	.popupCont {
		font-size: 26rpx;
	}

	.delTips {
		color: #FF0025;
	}

	.tab-box {
		/* margin-top: 80rpx; */
	}
	.bottom-fixed{
		bottom: 50px;
		/* height: calc(100vh - 240rpx); */
		/*  #ifdef  H5  */
		/* height: calc(100vh - 340rpx); */
		/*  #endif  */
	}
</style>
